package net.chrisrichardson.ec2deployer.core;

def class SarMonitor implements ProcessMonitor {

    def process
    def busyMetric = new Metric()
    def server
    def linesToSkip = 3

    def SarMonitor(EC2Server server) {
        this.server = server
    }

    void monitorProcess(Process p) {
        this.process = p
        Thread.startDaemon {readProcessIn(p.in)}
        Thread.startDaemon {System.err << p.err}
    }
    
    boolean isWaitForOrKillRequired() {
      false
    }
    
    void noteEndedOrTimedOut(Process process) {
    }


    public readProcessIn(is) {
        def line
        InputStreamReader isr = new InputStreamReader(is)
        while ((line = isr.readLine()) != null) {
            processLine(line)
        }
    }


    def processLine(line) {
        if (linesToSkip-- <= 0) {
            def elements = line.split(/ +/)
            def idleString = elements[7]
            def busy = 100.0 - Float.parseFloat(idleString)
            busyMetric << [busy, 200]
        }
    }

    def stop() {
        process.destroy()
    }

    def getAverageBusy() {
        busyMetric.average()
    }

    def start() {
        busyMetric = new Metric()
        linesToSkip = 3
        server.ssh("sar -u 5 0", null, this)
    }

    public void noteCommand(String command) {
        // Do nothing
    }
}
